<template>
  <el-dialog v-if="dialogFormVisible" v-el-drag-dialog :visible.sync="dialogFormVisible" :close-on-click-modal="false" :width="winWidth+'px'" :title="dialogTitle" @close="closeDialog">

    <div class="search-toolbar">
      <div v-if="searchColumns.length>0" class="left-toolbar-container">
        <!-- 高级搜索字段展示 -->
        <template v-for="(column,index) in searchColumns">
          <div v-if="column.listAdvSearchElement === 'input'" :key="index" class="advanced-search-field advanced-search-input">
            <span class="column-field-title">{{ column.title }}：</span>
            <el-input v-model="advancedSearchMap[column.field]" class="column-field-value" :placeholder="'请输入'+column.title" @input="doSearchText" @keyup.enter.native="doSearchText" />
          </div>
          <div v-else-if="column.listAdvSearchElement === 'select'" :key="index" class="advanced-search-field advanced-search-select">
            <span class="column-field-title">{{ column.title }}：</span>
            <el-select v-model="advancedSearchMap[column.field]" class="column-field-value" clearable :placeholder="'请选择'+column.title" @change="doSearchText">
              <el-option
                v-for="item in column.formatter"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
          </div>
          <div v-else-if="column.propType === 'java.util.Date' || (column.formatter&&column.formatter.toUpperCase().indexOf('MM') !== -1)" :key="index" class="advanced-search-field advanced-search-date">
            <span class="column-field-title">{{ column.title }}：</span>
            <el-date-picker
              v-model="advancedSearchMap[column.field]"
              class="column-field-value"
              :type="column.datePickerType"
              :placeholder="'请选择'+column.title"
              :format="column.formatter"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="doSearchText"
            />
          </div>
        </template>
      </div>
      <div class="right-toolbar-container">
        <!-- 普通搜索 -->
        <el-input v-model="searchText" class="search-input" placeholder="搜索..." :class="{'multiple-table':multiple}" clear="searchBar" @keyup.enter.native="doSearchText">
          <el-button slot="append" icon="el-icon-search" style="width:62px" @click.native="doSearchText" />
        </el-input>
        <el-button v-if="multiple" style="margin-left:10px" type="primary " icon="el-icon-check" @click="submitConfirm">确 定</el-button>
      </div>
    </div>

    <div class="listpage-dialog-container">
      <data-table
        :mode="'dialog'"
        :module-info="moduleInfo"
        :tb-columns="tbColumns"
        :toolbar-btns="listpageBtns"
        :on-cell-click="handleCellClick"
        :on-selected-rows-change="onSelectedRowsChange"
        :on-list-data-before-load="onListDataBeforeLoad"
        :on-list-data-loaded="onListDataLoaded"
      />
    </div>

    <Basicform
      v-if="formTitle!=''"
      :title="formTitle"
      :module-code="moduleInfo.moduleCode"
      :win-width="moduleInfo.winWidth"
      :win-height="moduleInfo.winHeight"
      :on-basic-form-before-open="onBasicFormBeforeOpen"
      :append-to-body="true"
    >
      <template>
        <busi-form :vo="formVo" :can-edit="formCanEdit" :module-info="moduleInfo" />
      </template>
    </Basicform>

  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
    props: {
        winWidth: { type: Number, default: 1200 }
    },
    data() {
        return {
            dialogTitle: '',
            dialogFormVisible: false,
            loading: false,
            el: null,
            binding: null,
            vnode: null,
            callback: null,
            multiple: false,
            moduleInfo: {},
            tbColumns: [],
            listpageBtns: [],
            selectedRows: [],
            searchText: '',
            formTitle: '',
            formVo: null,
            formCanEdit: 0,
            advancedSearchFields: '',
            searchColumns: [],
            advancedSearchMap: {},
            urlsearch: null
        }
    },
    computed: {
        ...mapGetters([
            'loginUser'
        ])
    },
    watch: {
    },
    created() {
        this.$bus.on('openListpageDialog', this.openListpageDialog)
    },
    beforeDestroy() {
        this.$bus.off('openListpageDialog', this.openListpageDialog)
    },
    mounted() {

    },
    methods: {
        openListpageDialog(el, binding, vnode) {
            const _this = this
            if (_this.loading) {
                return
            }
            _this.loading = true
            _this.searchText = ''

            this.el = el
            this.binding = binding
            this.vnode = vnode
            this.advancedSearchFields = this.el.attrs['advanced-search-fields'] ? this.el.attrs['advanced-search-fields'].split(',') : ''

            let listviewurl = this.el.attrs.listviewurl
            if (listviewurl.indexOf('urlsearch=') !== -1) {
                this.urlsearch = listviewurl.split('urlsearch=')[1].split('&')[0]

                if (this.urlsearch.indexOf('{vo.') !== -1) {
                    const usearchs = this.urlsearch.split('{vo.')
                    this.urlsearch = usearchs[0]
                    for (let i = 1; i < usearchs.length; i++) {
                        if (usearchs[i].indexOf('}') !== -1) {
                            const field = usearchs[i].split('}')[0]
                            if (vnode.context.vo[field] !== undefined && vnode.context.vo[field] !== null) {
                                this.urlsearch += vnode.context.vo[field]
                            }
                        }
                    }
                }
                listviewurl = listviewurl.substring(0, listviewurl.indexOf('?'))
            }

            let sysCode = ''
            if (this.$route.meta && this.$route.meta.sysCode) {
                sysCode += '?sysCode=' + this.$route.meta.sysCode
            }

            const reqParams = {
                method: 'GET',
                contentType: 'application/x-www-form-urlencoded',
                url: 'dcontent/getListpageInfo/' + listviewurl + '/' + sysCode
            }

            this.callback = vnode.context.onSelectListpageRowCompleted || vnode.context.$vnode.context.onSelectListpageRowCompleted || vnode.context.$vnode.context.$vnode.context.onSelectListpageRowCompleted

            this.$http(reqParams).then(res => {
                if (res.code === 'success') {
                    const attr = this.el.attrs
                    // 是否允许多选
                    if (attr.multiple || attr.multiple === 'true') {
                        this.multiple = true
                    } else {
                        this.multiple = false
                    }

                    const listpageInfo = res.body.listpage// 列表配置信息

                    if (el.attrs['dialog-title'] !== undefined) {
                        this.dialogTitle = el.attrs['dialog-title']
                    } else if (listpageInfo.listName.indexOf('>') !== -1) {
                        this.dialogTitle = listpageInfo.listName.substring(listpageInfo.listName.lastIndexOf('>') + 1)
                    } else {
                        this.dialogTitle = listpageInfo.listName
                    }

                    const moduleInfo = JSON.parse(listpageInfo.listModuleInfo)
                    moduleInfo.listpageId = listpageInfo.id
                    moduleInfo.listAdvSearchExpandPanel = 0

                    if (listpageInfo.listName.indexOf('>') !== -1) {
                        this.formTitle = listpageInfo.listName.substring(listpageInfo.listName.lastIndexOf('>') + 1)
                    } else {
                        this.formTitle = listpageInfo.listName
                    }

                    const tbColumns = JSON.parse(listpageInfo.listColumns)
                    const searchColumns = []

                    for (var i = 0; i < tbColumns.length; i++) {
                        if (this.multiple !== true && tbColumns[i].field === 'state') {
                            tbColumns.splice(i--, 1)
                            continue
                        } else if (attr['exclude-fields'] && attr['exclude-fields'].indexOf(tbColumns[i].field) !== -1) {
                            tbColumns.splice(i--, 1)
                            continue
                        } else if (tbColumns[i].propFormatter && tbColumns[i].propFormatter.indexOf('function：') !== -1) {
                            if (this.vnode.context[tbColumns[i].propFormatter.split('function：')[1]]) {
                                tbColumns[i].funcFormatter = this.vnode.context[tbColumns[i].propFormatter.split('function：')[1]]
                            } else if (this.vnode.context.$vnode.context[tbColumns[i].propFormatter.split('function：')[1]]) {
                                tbColumns[i].funcFormatter = this.vnode.context.$vnode.context[tbColumns[i].propFormatter.split('function：')[1]]
                            } else if (this.vnode.context.$vnode.context.$vnode.context[tbColumns[i].propFormatter.split('function：')[1]]) {
                                tbColumns[i].funcFormatter = this.vnode.context.$vnode.context.$vnode.context[tbColumns[i].propFormatter.split('function：')[1]]
                            }
                            tbColumns[i].propFormatter = ''
                        }

                        if (_this.advancedSearchFields && tbColumns[i] && _this.advancedSearchFields.indexOf(tbColumns[i].field) > -1 && !_this.advancedSearchMap[tbColumns[i].field]) {
                            searchColumns.push(JSON.parse(JSON.stringify(tbColumns[i])))
                            this.$set(this.advancedSearchMap, tbColumns[i].field, null)
                        }
                    }

                    this.searchColumnFormatter(searchColumns)

                    if (this.multiple !== true) {
                        tbColumns[tbColumns.length] = {
                            field: 'column_operate',
                            title: '操作',
                            width: '70px',
                            align: 'center',
                            valign: 'middle' }

                        this.listpageBtns = [{ 'id': 'btn_selectId', 'btnName': '选择', 'btnIcon': '', 'btnClick': this.selectOneRowCompleted, 'btnPermission': '', 'btnType': 'column' }]

                        let retaintns = el.attrs['retain-btns']
                        if (retaintns !== undefined && retaintns !== null) {
                            retaintns += ','
                            const toolbarBtns = JSON.parse(listpageInfo.listToolBtns)
                            const parentVue = this.$vnode.context.$vnode.context
                            for (let i = 0; i < toolbarBtns.length; i++) {
                                if (retaintns.indexOf(toolbarBtns[i].btnPermission) !== -1) {
                                    if (toolbarBtns[i].btnType === 'toolbar' && toolbarBtns[i].id === 'btn_add') {
                                        toolbarBtns[i].btnType = 'tbheader'
                                    } else if (toolbarBtns[i].btnType === 'column') {
                                        toolbarBtns[i].btnIcon = ''
                                    }
                                    this.listpageBtns.push(toolbarBtns[i])
                                }

                                const btnClick = toolbarBtns[i].btnClick
                                if (toolbarBtns[i].btnType === 'tbheader') {
                                    let btnParams = btnClick.substring(btnClick.indexOf('(') + 1, btnClick.lastIndexOf(')'))
                                    if (btnParams !== '') {
                                        btnParams = btnParams.replace(/'/g, '').split(',')
                                        toolbarBtns[i].btnParams = btnParams
                                    }
                                    toolbarBtns[i].cloumHeaderBtnClick = this.onCloumHeaderBtnClick
                                }

                                if (typeof parentVue[btnClick.split('(')[0]] === 'function') {
                                    toolbarBtns[i].btnClick = parentVue[btnClick.split('(')[0]]
                                }
                            }
                        }
                    }

                    this.moduleInfo = moduleInfo
                    this.tbColumns = tbColumns

                    this.dialogFormVisible = true
                } else {
                    this.$alert(res.message, { type: 'error' })
                }
                _this.loading = false
            })
        },
        searchColumnFormatter(searchColumns) {
            searchColumns.forEach(column => {
                var colFormater = column.propFormatter
                if (typeof colFormater === 'undefined' || colFormater === null || colFormater === '') colFormater = column.elementFormatter
                if (typeof colFormater === 'undefined' || colFormater === null) colFormater = ''

                if (column.propType === 'java.util.Date' || colFormater.toUpperCase().indexOf('MM') !== -1) {
                    var format = colFormater.replace(/\r\n/g, '').replace(/\r/g, '').replace(/\n/g, '')
                    if (format.indexOf('format：') === 0) {
                        format = format.substring(7)

                        column.formatter = format
                    } else {
                        column.formatter = 'yyyy-MM-dd HH:mm:ss'
                    }
                    if (column.formatter && column.formatter.indexOf(' HH:mm') !== -1) {
                        column.datePickerType = 'datetime'
                    } else {
                        column.datePickerType = 'date'
                    }
                } else {
                    const formatter = []
                    if (!column.formatter) {
                        var formatters = colFormater.replace(/\r\n/g, '<br>').replace(/\\r\\n/g, '<br>').replace(/\n/g, '<br>').replace(/\\n/g, '<br>').split('<br>')
                        for (let i = 0; i < formatters.length; i++) {
                            if (formatters[i].split('：').length > 1) {
                                const obj = {}
                                obj.value = formatters[i].split('：')[0]
                                obj.text = formatters[i].split('：')[1]
                                formatter.push(obj)
                            }
                        }
                        column.formatter = formatter
                    }
                }
            })
            this.searchColumns = searchColumns
        },
        onCloumHeaderBtnClick(btn) {
            if (btn.btnParams !== null) {
                btn.btnClick.apply(this.$vnode.context, btn.btnParams)
            } else {
                btn.btnClick.apply(this.$vnode.context)
            }
        },
        onListDataBeforeLoad($scope, qparams) {
            if (this.vnode.context.$vnode.context.onDialogListDataBeforeLoad) {
                this.vnode.context.$vnode.context.onDialogListDataBeforeLoad($scope, qparams)
            } else if (this.vnode.context.onDialogListDataBeforeLoad) {
                this.vnode.context.onDialogListDataBeforeLoad($scope, qparams)
            }

            if (this.urlsearch) {
                if (qparams.urlsearch) {
                    qparams.urlsearch += ';'
                } else {
                    qparams.urlsearch = ''
                }

                const searchs = this.urlsearch.split(';')
                searchs.forEach(search => {
                    if (qparams.urlsearch.indexOf(search) === -1) {
                        if (qparams.urlsearch) {
                            qparams.urlsearch += ';' + search
                        } else {
                            qparams.urlsearch = search
                        }
                    }
                })
            }

            for (const key in this.advancedSearchMap) {
                if (key !== undefined && this.advancedSearchMap[key] !== '' && this.advancedSearchMap[key] !== null && this.advancedSearchMap[key] !== undefined) {
                    if (qparams.urlsearch !== '')qparams.urlsearch += ';'
                    qparams.urlsearch += key + ' like ' + this.advancedSearchMap[key]
                }
            }
        },
        onListDataLoaded($scope, pageInfo) {
            this.searchColumns.forEach(column => {
                if (column.listAdvSearchElement === 'checkbox' || column.listAdvSearchElement === 'radio' || column.listAdvSearchElement === 'select') {
                    if (pageInfo.passenger && typeof pageInfo.passenger[column.field + 'Options'] === 'object' && pageInfo.passenger[column.field + 'Options'].length > 0) {
                        column.formatter = pageInfo.passenger[column.field + 'Options']
                    }
                }
            })

            if (process.env.NODE_ENV === 'development') console.log($scope.moduleInfo.moduleCode + ' listdata loaded')

            if (this.vnode.context.onDialogListDataLoaded) {
                this.vnode.context.onDialogListDataLoaded($scope, pageInfo)
            } else if (this.vnode.context.$vnode.context.onDialogListDataLoaded) {
                this.vnode.context.$vnode.context.onDialogListDataLoaded($scope, pageInfo)
            }
        },
        doSearchText() {
            this.$bus.emit('searchListData', this.searchText, 'or', 'dialog')
        },
        onBasicFormBeforeOpen($scope, vo, defer) {
            console.log($scope.moduleInfo.moduleCode + ' form before open')

            let formurl = this.moduleInfo.formTemplate.split('url=')[1]
            formurl = formurl.replace(/\//g, '.')
            formurl = '#/dcontent/vuebusiform/W/' + formurl.substring(1).replace('.html', '.vue')

            if ($scope.$route.meta && $scope.$route.meta.sysCode) {
                formurl += '?sysCode=' + $scope.$route.meta.sysCode
            } else if ($scope.vo.sysCode && $scope.vo.sysCode !== null && $scope.vo.sysCode !== '') {
                formurl += '?sysCode=' + $scope.vo.sysCode
            } else if ($scope.wfInstance) {
                formurl += '?sysCode=' + $scope.wfInstance.sysCode
            }

            this.$options.components['BusiForm'] = this.$loadComponent(formurl)

            this.formVo = vo
            this.formCanEdit = $scope.canEdit
            defer.resolve(true)
        },
        handleCellClick(row, column, cell, event) {
            console.log('listpage dialog table cell onclick,ignore ')
        },
        selectOneRowCompleted(row, column, cellValue, index) {
            this.selectedRows = [row]
            this.submitForm()
        },
        onSelectedRowsChange(selection) {
            this.selectedRows = selection
        },
        submitConfirm() {
            const model = this.vnode.data.model.expression
            const vo = model.split('.')[0]
            let value = ''
            if (model.split('.').length === 2) {
                value = this.vnode.context[vo][model.split('.')[1]]
            } else {
                value = this.vnode.context[vo]
            }

            if (this.selectedRows.length === 0 && value !== undefined && value !== null && value !== '') {
                this.$confirm('是否确认清除已选？').then(rst => {
                    this.submitForm()
                })
            } else {
                this.submitForm()
            }
        },
        submitForm() {
            if (this.callback !== undefined && this.callback !== null) {
                this.callback(this.selectedRows, this.el.attrs)
            } else {
                let selected = ''
                this.selectedRows.forEach(function(node) {
                    if (selected !== '') selected += '、'
                    selected += node.name || node.title || node.flSubject
                })
                const model = this.vnode.data.model.expression
                const vo = model.split('.')[0]

                if (this.vnode.context[vo]) {
                    let prop = ''
                    if (model.split('.').length === 2) {
                        prop = model.split('.')[1]
                    } else {
                        prop = vo
                    }
                    this.vnode.context.$set(this.vnode.context[vo], prop, selected)
                }
            }
            this.closeDialog()
        },
        closeDialog() {
            this.dialogFormVisible = false
            this.el = null
            this.binding = null
            this.vnode = null
            this.searchText = ''
            this.selectedRows = []
            this.moduleInfo = {}
            this.tbColumns = []
            this.searchColumns = []
            this.advancedSearchMap = {}
        }
    }
}
</script>

<style scoped lang="scss">
@import "~@/wapp/common/styles/variables.scss";

    .search-toolbar{
        display: flex;
        margin-bottom:10px;
        .left-toolbar-container{
            display: flex;
            .advanced-search-field{
                flex: 1;
                display: flex;
                margin-right: 10px;
                .column-field-title{ line-height: 36px;font-weight: 600; }
                .column-field-value{
                    flex: 1;
                }
            }
        }
        .right-toolbar-container{
            flex: 1;
            .search-input{width: 100%;}
            .multiple-table{
                width: calc(100% - 88px);
            }
            .searchBar{
                float: left;
            }
        }
    }
    /deep/ .el-link--inner{
        color: #1890ff;
    }
    /deep/ .el-table-toolbar{
        display: none;
    }
    /deep/ .content-column {
        cursor: unset;
    }
</style>
